package com.ltedu.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.ltedu.auth.domain.Oauth2Token;
import com.ltedu.common.contants.AuthConstants;
import com.ltedu.common.enums.ErrorCodeEnum;
import com.ltedu.common.exception.BaseException;
import com.ltedu.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.Map;

@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @PostMapping("/token")
    public Result postAccessToken(Principal principal, @RequestParam Map<String, String> parameters)
            throws HttpRequestMethodNotSupportedException {
        String clientId = parameters.get("client_id");
        if (StrUtil.isBlank(clientId)) {
            throw new BaseException(ErrorCodeEnum.CLIENT_ID_NOT_NULL);
        }

        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Oauth2Token oauth2Token = Oauth2Token.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
//                .tokenHead(AuthConstants.JWT_TOKEN_PREFIX)
                .build();
        return Result.ok(oauth2Token);
    }

    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }

}